package lumingweihua.future.cn.lumingweihua.home.cheyuan;

import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.TextView;

import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialog;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialogEntity;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.Constant;
import lumingweihua.future.cn.lumingweihua.MainActivity;
import lumingweihua.future.cn.lumingweihua.R;
import lumingweihua.future.cn.lumingweihua.home.domain.CheyuanData;
import lumingweihua.future.cn.lumingweihua.person.domain.LoginData;
import lumingweihua.future.cn.lumingweihua.person.domain.PersonData;
import lumingweihua.future.cn.lumingweihua.release.ReleaseCarActivity;
import lumingweihua.future.cn.lumingweihua.ui.mine.GoodsBossActivity;
import lumingweihua.future.cn.lumingweihua.ui.mine.MineCarActivity;

/**
 * Created by Administrator on 2018/3/3.
 */

public class CheyuanDetailActivity extends BaseActivity {
    @Override
    protected void initView() {
        setContentView(R.layout.activity_cheyuan_detail);
        initTitleBar("车源详情", Constant.DEFAULT_LEFT_BACK, null);

        findViewById(R.id.bt_phone).setOnClickListener(this);
    }

    private boolean isMine;
    private CheyuanData cd;
    @Override
    protected void initData() {
        isMine = getIntentExtra("isMine",true);
        requestData();
        requestPersonData(REQUEST_PERSON2);
    }

    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.bt_phone:
                CommonUtils.readyCall(context,cd.getHot_line());
                break;
            case R.id.tv_address:
                startActivity(new Intent(context,LocationActivity.class)
                .putExtra("lat",cd.getLat())
                .putExtra("lon",cd.getLon())
                );
                break;
            case R.id.bt_ok:
                if(isMine){
                    if("2".equals(cd.getSource_status())){
                        //展示中,删除
                        new YesOrNoDialog(context, new YesOrNoDialogEntity("确定删除吗？\n删除后，车源将不在APP显示", "取消", "确认"),
                                new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                                    @Override
                                    public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                        switch (yesOrNoType) {
                                            case BtnOk:
                                                requestDel();
                                                break;

                                            default:
                                                break;
                                        }
                                    }
                                }).show();
                    }else if("3".equals(cd.getSource_status())){
                        //修改车源信息
                        startActivity(new Intent(context,ReleaseCarActivity.class)
                        .putExtra("car_id",cd.getCar_id())
                        .putExtra("license",cd.getCarnum())
                        .putExtra("origin",cd.getStartCity())
                        .putExtra("destination",cd.getEndCity())
                        .putExtra("empty",cd.getAddress())
                        .putExtra("lat",cd.getLat())
                        .putExtra("lon",cd.getLon())
                        .putExtra("time",cd.getUnableTime())
                        );
                    }
                }else{
                    if(cd.getIsself())
                        jumpToNextActivity(MineCarActivity.class,false);
                    else{
                        //发出邀请
                        requestPersonData(REQUEST_PERSON);
                    }
                }


                break;

            default:
                break;
        }
    }

    /** 请求标识 **/
    private final int REQUEST_SET = 0;
    private final int REQUEST_DATA = 1;
    private final int REQUEST_DEL = 2;
    private final int REQUEST_PERSON = 4;
    private final int REQUEST_PERSON2 = 5;
    /**
     * 公共个人信息
     */
    private void requestPersonData(int reqid) {
		showProgressBar(null);

        BeanRequest<PersonData, DefaultMamahaoServerError> req = new BeanRequest<>(
                context,
                "",
                this, PersonData.class);

        req.setParam("apiCode", "_userinfo_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, reqid);
    }

    /**
     * 请求注册
     */
    private void requestData() {
        showProgressBar(null);

        BeanRequest<CheyuanData, DefaultMamahaoServerError> req = new BeanRequest<>(
                context,
                "",
                this, CheyuanData.class);


        req.setParam("apiCode", isMine?"_usercarsource_details_001":"_car_particulars_001");
        req.setParam("id", getIntentExtra("id"));
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_DATA, new ReqTag.Builder().handleSimpleRes(true));
    }

    /**
     * 邀请司机
     */
    private void requestSet(){
        showProgressBar(null);

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context,"",this);

        req.setParam("apiCode", "_invite_car_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());
        //传这个参数代表修改，没有代表新增地址
        req.setParam("id", getIntentExtra("id"));

		//获取token
		String token = NetworkManager.getInstance().getPostToken(req.getParam());
		req.setParam("token", token);

        addRequestQueue(req, REQUEST_SET, new ReqTag.Builder().handleSimpleRes(true));
    }

    /**
     * 邀请司机
     */
    private void requestDel(){
        showProgressBar(null);

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context,"",this);

        req.setParam("apiCode", "_delete_carsource_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());
        //传这个参数代表修改，没有代表新增地址
        req.setParam("id", getIntentExtra("id"));

		//获取token
		String token = NetworkManager.getInstance().getPostToken(req.getParam());
		req.setParam("token", token);

        addRequestQueue(req, REQUEST_DEL, new ReqTag.Builder().handleSimpleRes(true));
    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        // TODO Auto-generated method stub
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_SET:
                // 设置成功
                new YesOrNoDialog(context, new YesOrNoDialogEntity("邀请消息已通过短信方式发送给车主，请耐心等待车主与您联系", null, "我知道啦"),
                        new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                            @Override
                            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                switch (yesOrNoType) {
                                    case BtnOk:
                                        setResult(RESULT_OK);
                                        finish();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        }).show();
                break;
            case REQUEST_DATA:
                cd = (CheyuanData) data;
                setText(R.id.tv_name,isMine?cd.getCar_name():cd.getName());
                setText(R.id.tv_carnum,cd.getCarnum());
                setText(R.id.tv_start_city,cd.getStartCity());
                setText(R.id.tv_end_city,cd.getEndCity());
                setText(R.id.tv_address,cd.getAddress());
                setText(R.id.tv_time,cd.getTime());
                setText(R.id.tv_quality,cd.getQuality());
                setText(R.id.tv_weight,cd.getWeight());

                TextView bt_ok = findViewById(R.id.bt_ok);
                if(isMine){
                    findViewById(R.id.rl_tip).setVisibility(View.VISIBLE);
                    findViewById(R.id.tv_count_time).setVisibility(View.VISIBLE);

                    if("2".equals(cd.getState())){
                        //已失效
                        bt_ok.setVisibility(View.GONE);
                        setText(R.id.tv_count_time,"该车源信息已在"+cd.getUnableTime()+"失效");
                    }else if("1".equals(cd.getSource_status())){
                        //待审核
                        bt_ok.setVisibility(View.GONE);
                        setText(R.id.tv_count_time,"车源信息审核中，请耐心等待...");
                    }else if("2".equals(cd.getSource_status())){
                        //展示中
                        bt_ok.setText("删除");
                        bt_ok.setOnClickListener(this);
                        setText(R.id.tv_count_time,"该车源信息将在"+cd.getUnableTime()+"失效");
                    }else if("3".equals(cd.getSource_status())){
                        //拒绝
                        bt_ok.setText("修改车源信息");
                        bt_ok.setOnClickListener(this);
                        setText(R.id.tv_count_time,"拒绝原因：\n"+cd.getReject_reason());
                    }
                }else{
                    if("1".equals(cd.getState())){
                        //已发出邀请
                        bt_ok.setText("已发出邀请，请等待");
                        bt_ok.setBackgroundColor(Color.parseColor("#cccccc"));
                    }else{
                        bt_ok.setOnClickListener(this);
                        if(cd.getIsself())
                            bt_ok.setText("管理我的车源");
                    }
                }


                findViewById(R.id.tv_address).setOnClickListener(this);
                break;
            case REQUEST_DEL:
                showToast("删除成功");
                setResult(RESULT_OK);
                finish();
                break;
            case REQUEST_PERSON2:
                if(((PersonData)data)!=null){
                    if(((PersonData)data).getIsFinishDriverAuth() || ((PersonData)data).getIsFinishCarAuth())
                        setText(R.id.bt_phone,"拨打电话");
                }else{

                }
                break;
            case REQUEST_PERSON:
                PersonData personData = (PersonData)data;
                if(personData!=null && personData.getIsFinishDriverAuth()){
                    //完成认证
                    new YesOrNoDialog(context, new YesOrNoDialogEntity("确定向该司机发出邀请吗?", "取消", "确认"),//每个车源只能发起"+MainActivity.instance.personData.getInviteTime()+"次请求哦!
                            new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                                @Override
                                public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                    switch (yesOrNoType) {
                                        case BtnOk:
                                            requestSet();
                                            break;

                                        default:
                                            break;
                                    }
                                }
                            }).show();
                }else{
                    //去认证
                    new YesOrNoDialog(context, new YesOrNoDialogEntity("完成货主认证后，才能邀请司机", "暂不认证", "立即认证"),
                            new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                                @Override
                                public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                    switch (yesOrNoType) {
                                        case BtnOk:
                                            jumpToNextActivity(GoodsBossActivity.class,false);
                                            break;

                                        default:
                                            break;
                                    }
                                }
                            }).show();
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error, AbstractRequest.MamaHaoError clientError) {
        super.onResponseFailure(tag, error, clientError);
    }
}
